﻿using BenchmarkDotNet.Attributes;
using System;

[MemoryDiagnoser]
public class SortingBenchmark
{
    private int[] array;
    [Params(1000, 10000, 100000)] // 定义不同规模的数组作为参数
    public int ArraySize { get; set; }
    [GlobalSetup]
    public void Setup()
    {
        // 初始化待排序的数组
        array = new int[ArraySize];
        Random random = new Random();
        for (int i = 0; i < ArraySize; i++)
        {
            array[i] = random.Next();
        }
    }
    [Benchmark]
    public void BubbleSort()
    {
        // 冒泡排序算法实现
        for (int i = 0; i < ArraySize - 1; i++)
        {
            for (int j = 0; j < ArraySize - i - 1; j++)
            {
                if (array[j] > array[j + 1])
                {
                    int temp = array[j];
                    array[j] = array[j + 1];
                    array[j + 1] = temp;
                }
            }
        }
    }
    [Benchmark]
    public void QuickSort()
    {
        // 快速排序算法实现
        QuickSort(array, 0, ArraySize - 1);
    }
    private void QuickSort(int[] arr, int low, int high)
    {
        if (low < high)
        {
            int pivot = Partition(arr, low, high);
            QuickSort(arr, low, pivot - 1);
            QuickSort(arr, pivot + 1, high);
        }
    }
    private int Partition(int[] arr, int low, int high)
    {
        int pivot = arr[high];
        int i = low - 1;
        for (int j = low; j < high; j++)
        {
            if (arr[j] < pivot)
            {
                i++;
                int temp = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;
            }
        }
        int temp2 = arr[i + 1];
        arr[i + 1] = arr[high];
        arr[high] = temp2;
        return i + 1;
    }
}